//
//  String+regex.swift
//  OnemeetingDemo
//
//  Created by 张衡 on 2020/5/21.
//  Copyright © 2020 www.onemeeting.1meetingIos. All rights reserved.
//

import Foundation


//正则
extension String {
    /// 正则匹配
    ///
    /// - Parameters:
    ///   - regex: 匹配规则
    ///   - validateString: 匹配对test象
    /// - Returns: 返回结果
    func regularExpression (regex:String) -> [String]{
        do {
            let validateString:String = self
            let regex: NSRegularExpression = try NSRegularExpression(pattern: regex, options: [])
            let matches = regex.matches(in: validateString, options: [], range: NSMakeRange(0, validateString.count))
            
            var data:[String] = Array()
            for item in matches {
                let string = (validateString as NSString).substring(with: item.range)
                data.append(string)
            }
            
            return data
        }
        catch {
            return []
        }
    }
    
    /// 字符串是否有效
    ///
    /// - Parameters:
    ///   - validateString: 匹配对象
    ///   - regex: 匹配规则
    /// - Returns: 结果
    func isMatchedBy(regex:String) -> Bool {
        do {
            let validateString:String = self
            let RE = try NSRegularExpression(pattern: regex, options: .caseInsensitive)
            let modified = RE.matches(in: validateString, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSRange.init(location: 0, length: validateString.lengthcount))
            return modified.count>0
        }
        catch {
            return false
        }
       
    }

    
    /// 字符串的替换
    ///
    /// - Parameters:
    ///   - validateString: 匹配对象
    ///   - regex: 匹配规则
    ///   - content: 替换内容
    /// - Returns: 结果
    func replace(regex:String,content:String) -> String {
        
        let validateString:String = self
        do {
            let RE = try NSRegularExpression(pattern: regex, options: .caseInsensitive)
            let modified = RE.stringByReplacingMatches(in: validateString, options: .reportProgress, range: NSRange(location: 0, length: validateString.count), withTemplate: content)
            return modified
        }
        catch {
            return validateString
        }
       
    }
}
